package com.sui.bigdata.sml.web.service.impl;

import com.sui.bigdata.sml.web.dto.ComponentCategoryDTO;
import com.sui.bigdata.sml.web.dto.ComponentDTO;
import com.sui.bigdata.sml.web.service.ComponentService;
import com.sui.bigdata.sml.web.exception.EntityNotFoundException;
import com.sui.bigdata.sml.web.repository.mapper.ComponentMapper;
import com.sui.bigdata.sml.web.repository.model.Component;
import com.sui.bigdata.sml.web.repository.model.ComponentCategory;
import lombok.extern.slf4j.Slf4j;
import ma.glasnost.orika.MapperFacade;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.DependsOn;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author songhaicheng
 * @date 2019/11/5 13:49
 * @description
 * @reviewer
 */
@Service
@DependsOn("disconfConfig")
@Slf4j
public class ComponentServiceImpl implements ComponentService {

    @Autowired
    private ComponentMapper mapper;
    @Autowired
    private MapperFacade mapperFacade;

    @Override
    public Long add(ComponentDTO dto) {
        Component component = mapperFacade.map(dto, Component.class);
        mapper.insert(component);
        return component.getId();
    }

    @Override
    public ComponentDTO get(Long id) {
        Component component = mapper.get(id);
        if (component == null) {
            throw new EntityNotFoundException(Component.class, id);
        }
        return mapperFacade.map(component, ComponentDTO.class);
    }

    @Override
    public Boolean update(ComponentDTO dto) {
        // 防止更新的数据不存在
        get(dto.getId());
        Component component = mapperFacade.map(dto, Component.class);
        return mapper.update(component) == 1;
    }

    @Override
    public Boolean delete(Long id) {
        get(id);
        return mapper.delete(id) == 1;
    }

    @Override
    public List<ComponentDTO> listAll() {
        return mapperFacade.mapAsList(mapper.list(), ComponentDTO.class);
    }

    @Override
    public Integer addCategory(ComponentCategoryDTO dto) {
        ComponentCategory category = mapperFacade.map(dto, ComponentCategory.class);
        mapper.insertCategory(category);
        return category.getId();
    }

    @Override
    public Boolean updateCategory(ComponentCategoryDTO dto) {
        if (mapper.getCategory(dto.getId()) == null) {
            throw new EntityNotFoundException(ComponentCategory.class, dto.getId());
        }
        ComponentCategory category = mapperFacade.map(dto, ComponentCategory.class);
        return mapper.updateCategory(category) == 1;
    }

    @Override
    public List<ComponentCategoryDTO> listAllCategories() {
        return mapperFacade.mapAsList(mapper.listCategories(), ComponentCategoryDTO.class);
    }

}
